package com.sk.utility;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Hashtable;

import com.sk.utility.Constants.FeedID;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

/**
 * Async task to download JSON feed in background thread
 * 
 * @author saurabh
 */
public class FeedDownloadTask extends
		AsyncTask<String, Void, Hashtable<String, String>> {
	private final WeakReference<AsyncTaskCompleteListener> callback;
	private final WeakReference<Context> context;

	public FeedDownloadTask(AsyncTaskCompleteListener cb, Context ctx) {
		this.callback = new WeakReference<AsyncTaskCompleteListener>(cb);
		this.context = new WeakReference<Context>(ctx);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	protected void onPostExecute(Hashtable<String, String> feed) {
		if (isCancelled()) {
			feed = null;
		}
		AsyncTaskCompleteListener cb = callback.get();
		final String url = feed.get("url");
		if (url != "") {
			// start write to cache
			Context ctx = context.get();
			FileCache fileCache = new FileCache(ctx);
			fileCache.putFile(feed);
			// end write to cache
			Log.i("FeedDownloadTask", "Downloaded feed from " + url);
		} else {
			Log.i("FeedDownloadTask", "Loaded feed from cache");
		}
		cb.onTaskComplete(feed.get("feed"), FeedID.FEED);
	}

	@Override
	protected Hashtable<String, String> doInBackground(String... urls) {
		Hashtable<String, String> feed;
		Context ctx = context.get();
		FileCache fileCache = new FileCache(ctx);
		File f = fileCache.getFileName(urls[0]);
		if (f.exists()) {
			final String feedStr = fileCache.getFile(f);
			feed = new Hashtable<String, String>();
			feed.put("url", "");
			feed.put("feed", feedStr);
		} else {
			Connection json = new Connection();
			feed = json.GetJSONFeed(urls[0]);
		}
		return feed;
	}
}